import {
    api,
} from '@/lib/api';
import {
    url,
} from '@/lib/utils';
import Vue from 'vue';
import { Module } from 'vuex';
import { RootState } from '@/types/store';

export interface CommunityState {
    videoList: any;
    videoDetailMap: any;
    commentsMap: any;
    /** 是否正在进行点赞操作 */
    thumbUpRequesting: any;
}

const m: Module<CommunityState, RootState> = {
    namespaced: true,
    state: {
        videoList: null,
        videoDetailMap: {},
        commentsMap: {},
        /** 是否正在进行点赞操作 */
        thumbUpRequesting: false,
    },
    mutations: {
        /** 初始化视频列表 */
        initVideoList(state) {
            state.videoList = {
                list: [],
                loaded: false,
                req: false,
            };
        },
        concatVideoList(state, { list }) {
            const ids = [];
            list.forEach(item => {
                ids.push(item.id);
                Vue.set(state.videoDetailMap, item.id, item);
            });
            state.videoList.list.push(...ids);
        },
        setVideoListReq(state, { req }) {
            state.videoList.req = req;
        },
        setVideoListLoaded(state, { loaded }) {
            state.videoList.loaded = loaded;
        },
        // 标记是否正在进行点赞操作
        setThumbUpRequesting(state, status) {
            state.thumbUpRequesting = status;
        },
        /**
         * 是否点赞
         *
         * @param {Number} postId 动态Id
         * @param {Boolean} thumbUp 点赞
         */
        setThumbUp(state, { postId, thumbUp }) {
            if (state.videoDetailMap[postId]) {
                const temp = Number(state.videoDetailMap[postId].thumb_up_number);
                const count = thumbUp ? temp + 1 : temp - 1;
                Vue.set(state.videoDetailMap[postId], 'thumb_up_number', count);
                Vue.set(state.videoDetailMap[postId], 'has_thumb_up', thumbUp);
            }
        },
        setComments(state, { postId, list }) {
            Vue.set(state.commentsMap, postId, list);
        },
        insertComment(state, { postId, comment }) {
            if (state.commentsMap[postId]) {
                state.commentsMap[postId].push(comment);
            }
            if (state.videoDetailMap[postId]) {
                Vue.set(state.videoDetailMap[postId], 'comment_number', Number(state.videoDetailMap[postId]['comment_number']) + 1);
            }
        },
        setVideoDetail(state, { postId, detail }) {
            Vue.set(state.videoDetailMap, postId, detail);
        },
    },

    actions: {
        async getVideoList({ state, commit }, { offset, count, forceUpdate }) {
            if (forceUpdate || !state.videoList) {
                commit('initVideoList');
            }
            const wrap = state.videoList;
            const length = wrap.list.length;
            const end = offset + count;
            if (wrap.loaded || wrap.req) {
                return;
            }
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - length;
            }
            commit('setVideoListReq', { req: true });
            const res = await api.get({
                url: `${url}/api/video`,
                data: {
                    offset,
                    count,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatVideoList', {
                    list,
                });
                if (list.length < count) {
                    commit('setVideoListLoaded', {
                        loaded: true,
                    });
                }
            }
            commit('setVideoListReq', { req: false });
            return res;
        },
        async getVideoDetail({ state, commit }, { postId }) {
            const res = await api.get({
                url: `${url}/api/video/detail`,
                data: {
                    id: postId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const detail = res.data.data;
                commit('setVideoDetail', {
                    postId,
                    detail,
                });
            }
            return res;
        },
        /**
        * 点赞/取消点赞
        * @param {Number} postId 动态Id
        * @param {Boolean} thumbUp 是否进行点赞
        */
        async thumbUp({ state, commit }, { postId, thumbUp }) {
            // 开始更新数据
            commit('setThumbUpRequesting', true);
            const response = await api.post({
                url: `${url}/api/video/thumb_up`,
                data: {
                    id: postId,
                },
            });
            const rdata = response.data;
            if (rdata.status === 0 && response.statusCode === 200) {
                // console.log('thumbUp', thumbUp);
                commit('setThumbUp', {
                    postId,
                    thumbUp,
                });
            } else {
                wx.showToast({
                    title: `系统繁忙，稍后重试`,
                    icon: 'none',
                });
            }
            commit('setThumbUpRequesting', false);
            return rdata;
        },
        /** 获取评论 */
        async getVideoComment({ state, commit }, { postId }) {
            const response = await api.get({
                url: `${url}/api/video/comment`,
                data: {
                    id: postId,
                },
            });
            const rdata = response.data;
            if (rdata.status === 0 && response.statusCode === 200) {
                commit('setComments', {
                    postId,
                    list: rdata.data,
                });
            }
            return rdata;
        },
        /**
         * 对某条动态进行评论
         * @param {Number} postId 动态ID
         * @param {String} content 评论的内容
         */
        async publishComment({ state, commit, rootState }, { postId, content }) {
            const user = rootState.utils.userBasicInfo;
            // console.log('user', user, rootState);
            const response = await api.post({
                url: `${url}/api/video/comment`,
                data: {
                    id: postId,
                    content,
                },
            });
            const rdata = response.data;
            if (rdata.status === 0 && response.statusCode === 200) {
                const comment = {
                    nickname: user.nickname,
                    avatar: user.avatar,
                    content,
                };
                commit('insertComment', {
                    postId,
                    comment,
                });
            }
            return rdata;
        },
    },
};

export default m;
